package com.ihr360.payroll.service.attendanceplan.impl;

import com.ihr360.payroll.dao.SickLeaveRuleRepository;
import com.ihr360.payroll.model.dto.attendance.rule.sickleave.SickLeaveRule;
import com.ihr360.payroll.service.attendanceplan.SickLeaveRuleService;
import com.ihr360.rest.reposity.SimpleRestReposity;
import com.ihr360.rest.service.AbstractSimpleRestServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author tomtao
 */
@Service
public class SickLeaveRuleServiceImpl extends AbstractSimpleRestServiceImpl<SickLeaveRule, Long> implements SickLeaveRuleService {

    @Autowired
    SickLeaveRuleRepository sickLeaveRuleRepository;

    @Override
    public SimpleRestReposity<SickLeaveRule, Long> getSimpleRestReposity() {
        return sickLeaveRuleRepository;
    }

    @Override
    public SickLeaveRule save(SickLeaveRule sickLeaveRule) {
        if(sickLeaveRule.getId() != null) {
            SickLeaveRule ret = sickLeaveRuleRepository.findOne(sickLeaveRule.getId());
            if(ret == null) {
                return null;
            }

            if(sickLeaveRule.getAdvancedDeductionEnable() == null
                    || !sickLeaveRule.getAdvancedDeductionEnable()) {
                ret.setAdvancedDeductionEnable(false);
                ret.setDeductConfig(null);
                ret.setDeductionBy(null);
            } else {
                ret.setAdvancedDeductionEnable(true);
                ret.setDeductConfig(sickLeaveRule.getDeductConfig());
                ret.setDeductionBy(sickLeaveRule.getDeductionBy());
            }
            ret.setBasementType(sickLeaveRule.getBasementType());
            ret.setBaseRatio(sickLeaveRule.getBaseRatio());
            ret.setFixedBase(sickLeaveRule.getFixedBase());
            ret.setNumOpRatio(sickLeaveRule.getNumOpRatio());
            ret.setReferenceFields(sickLeaveRule.getReferenceFields());
            ret.setRemark(sickLeaveRule.getRemark());
            ret.setUpdatedAt(new Date());
            return sickLeaveRuleRepository.save(ret);
        }
        return sickLeaveRuleRepository.save(sickLeaveRule);
    }
}
